package com.ruoyi.web.controller.app.pay.alipay.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.demo.trade.config.Configs;
import com.google.common.collect.Maps;
import com.ruoyi.web.controller.app.pay.alipay.service.IAliPayService;
import com.ruoyi.web.controller.app.pay.alipay.util.AliPayConfig;
import com.ruoyi.web.controller.app.pay.constants.NewsConstants;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;

@Service
public class AliPayServiceImpl implements IAliPayService {
	private static final Logger logger = LoggerFactory.getLogger(AliPayServiceImpl.class);

	@Value("${alipay.notify.url}")
	private String notify_url;

	/*@Autowired
	private AppCostOrderMapper orderMapper;

	@Autowired
	private OrderGoodsMapper orderGoodsMapper;

	@Autowired
	private UserInfoMapper userInfoMapper;

	@Autowired
	private StoreAccountMapper storeAccountMapper;
	@Autowired
	private FlowMapper flowMapper;
	@Autowired
	private CarMapper carMapper;

	@Autowired
	private CategoryMapper categoryMapper;
	@Autowired
	private StoreMapper storeMapper;
	@Autowired
	private AppCostOrderMapper costOrderMapper; //物业订单支付
	@Autowired
	private AppCostRecordMapper recordMapper; //物业订单流水*/

	private DecimalFormat df = new DecimalFormat("0.00");

	@Override
	public String appPay(String uid, Long orderId) throws JSONException,UnsupportedEncodingException {

		String orderString = NewsConstants.FAIL;

		//1、AppCostOrder order = orderMapper.selectById(orderId);

		// 实例化客户端
		AlipayClient alipayClient = AliPayConfig.getAlipayClient();
		// 实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
		AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
		// SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
		AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();


		//1、double money =  CommonUtil.getNewDouble(order.getPaymoney(), 2);

		//1、String moneystr = CommonUtil.numberFormat(2, money);

		model.setBody("微信支付");
		model.setSubject("智慧物业");
		//1、model.setOutTradeNo(order.getOrderNo());
		model.setTimeoutExpress("30m");
		//1、model.setTotalAmount(moneystr);
		model.setProductCode("QUICK_MSECURITY_PAY");

		JSONObject josn = new  JSONObject();
		josn.put("userId", uid);
		model.setPassbackParams(URLEncoder.encode(josn.toString(), "utf-8"));
		request.setBizModel(model);
		//商户外网可以访问的异步地址
		request.setNotifyUrl(notify_url);
		try {
			// 这里和普通的接口调用不同，使用的是sdkExecute
			AlipayTradeAppPayResponse response = alipayClient
					.sdkExecute(request);
			orderString  = response.getBody();//就是orderString 可以直接给客户端请求，无需再做处理。
			System.out.println(orderString);
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		return orderString;
	}



	@Override
	@Transactional(rollbackFor = RuntimeException.class)
	public void notifyUrl(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException, JSONException, UnsupportedEncodingException{
		System.out.println("进入支付宝回调>>>>>>>>>>>>>>>");
		Map<String, String[]> map = request.getParameterMap();
		ConcurrentMap<String, String> param = Maps.newConcurrentMap();
		map.forEach((k, v) -> {
			if (v.length > 0) {
				param.put(k, v[0]);
			}
			if (v.length > 1) {
				param.put(k, v[1]);
			}
		});
		//处理数据
		boolean boo = com.alipay.api.internal.util.AlipaySignature.rsaCheckV1(param, Configs.getAlipayPublicKey(), "utf-8", "RSA2");

		if (boo) { //签名验证成功
			//验证金额
			String jsonpar = URLDecoder.decode(param.get("passback_params"), "utf-8"); //自定义参数

			String out_trade_no = param.get("out_trade_no"); //订单号

			//String subject = param.get("subject");

			String appid = param.get("app_id");  //appId
			String total_amount = param.get("total_amount");//订单金额

			String trade_status = param.get("trade_status"); //交易状态  TRADE_SUCCESS 支付成功

			if (trade_status.equals("TRADE_SUCCESS")) { //为真 支付成功
				//效验金额
				//1、AppCostOrder order = orderMapper.selectByOrderNo(out_trade_no);
				//1、double money = order.getPaymoney();
			/*	1、if (order != null && money == Double.valueOf(total_amount) && Configs.getAppid().equals(appid)) {
					System.out.println("支付宝回调验证通过>>>>>>>>>>>>>>>");
					JSONObject json = new JSONObject(jsonpar);
					String userId = json.getString("userId");

					//更改订单为已支付
						*//*sql:update property_cost_pay_order set order_status = #{status} where order_no = #{orderNo}
						costOrderMapper.updateStatus(map);*//*
					order.setOrderStatus(1);
					order.setPayTime(new Date());
					orderMapper.updateById(order);

					//生缴费记录
					   *//*sql:INSERT INTO property_house_cost_record(order_type,order_no,money,pay_type,pay_time)
						VALUES(#{orderType},#{orderNo},#{money},#{payType},#{payTime})
						recordMapper.addRecord(map);*//*
					String flowNo=String.valueOf(System.currentTimeMillis()/1000)+userId;
					AppPayRecord payRecord = AppPayRecord.builder()
							.money(money).orderNo(flowNo).userId(userId).orderType("1").PayTime(new Date()).payType(1).build();
					recordMapper.insert(payRecord);

					PrintWriter pw = null;
					try {
						pw = response.getWriter();
						pw.println("success");
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						pw.close();
					}
				}*/
			}
		}
	}

}
